package com.bauer.java.drools;

import org.apache.commons.io.IOUtils;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message.Level;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.io.IOException;

/**
 * @Author ：rui.wei
 * @Date ：Created in 16:57 2018/8/24
 * @Description：
 */
public class KieModuleModelExample {

    public static void main(String[] args) throws IOException {
        KieServices kieServices = KieServices.Factory.get();
        KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
        KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("Test");
        KieSessionModel kieSessionModel = kieBaseModel.newKieSessionModel("sdfasdf");
        KieFileSystem kfs = kieServices.newKieFileSystem();
        String ruleTemplate = IOUtils
                .toString(KieModuleModelExample.class.getResourceAsStream("/user.drl"),  "UTF-8");
        kfs.write("src/main/resources/drools/hello.drl",ruleTemplate);

        kfs.writeKModuleXML(kieModuleModel.toXML());
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        System.out.println(kieBuilder.getResults().getMessages(Level.ERROR).size());
        KieContainer kContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
        User user = new User();
        user.setAge(21);
        user.setAdu(2);
        user.setName("jhah");
        KieSession kieSession = kContainer.newKieSession("sdfasdf");
        kieSession.insert(user);
        kieSession.fireAllRules();
        kieSession.dispose();
    }
}
